package com.imay.live;

import android.app.Activity;
import android.content.Context;
import android.support.multidex.MultiDex;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.facebook.cache.disk.DiskCacheConfig;
import com.facebook.common.internal.Supplier;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.cache.MemoryCacheParams;
import com.facebook.imagepipeline.core.ImagePipelineConfig;
import com.imay.base.BaseApplication;
import com.imay.base.helper.ActivityHelper;
import com.imay.base.helper.NetworkHelper;
import com.imay.cocos.IMayCocos;
import com.imay.live.application.NimApplication;
import com.imay.live.helper.RepostHelper;
import com.imay.live.helper.RoomNoticeHelper;
import com.imay.live.helper.ShareNoticeHelper;
import com.imay.live.helper.UmengPushHelper;
import com.imay.live.helper.UrlHelper;
import com.imay.live.manager.AccountManager;
import com.imay.live.manager.MessageManager;
import com.imay.live.manager.UnreadManager;
import com.imay.live.proto.ProtoResult;
import com.imay.live.proto.Result;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.proto.helper.ProtoSocketFactory;
import com.imay.live.utils.AppUtil;
import com.imay.live.utils.FileUtil;
import com.imay.live.utils.ToastUtil;
import com.imay.live.wxapi.WXPayEntryActivity;
import com.imay.tbas_api.IMYScheduler;
import com.netease.nim.uikit.NimUIKit;
import com.tencent.bugly.crashreport.CrashReport;
import com.umeng.socialize.Config;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;

import java.io.File;

/**
 * Created by jeaman on 2017/2/16.
 */

public class IMApplication extends NimApplication implements ActivityHelper.OnAppListener {
    protected boolean mIsProtectMode = false;
    private static IMApplication instance;

    private long currentChatUid;

    public static IMApplication getInstance() {
        return instance;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    protected void init() {
        instance = this;
        CrashReport.initCrashReport(getApplicationContext(), BuildConfig.IS_RELEASE ? "4604733b90" : "53b0daf6dc", false);  //bugly区分正式环境和测试环境
        Constants.sChannelName = AppUtil.getChannel(this);  //渠道号
        Config.DEBUG = false;
        UMShareAPI.get(this);
        MultiDex.install(this);
        DiskCacheConfig diskCacheConfig = DiskCacheConfig.newBuilder(instance)
                .setBaseDirectoryName("Fresco")
                .setBaseDirectoryPathSupplier(new Supplier<File>() {
                    @Override
                    public File get() {
                        return new File(FileUtil.getDiskCacheDir());
                    }
                }).build();
        ImagePipelineConfig.Builder configBuilder = ImagePipelineConfig.newBuilder(instance);
        // 设置内存配置
        int maxMemory = (int) Runtime.getRuntime().maxMemory();
        int cacheSize = maxMemory / 4;
        final MemoryCacheParams bitmapCacheParams = new MemoryCacheParams(
                cacheSize, // Max total size of elements in the cache
                200,                     // Max entries in the cache
                200 * 1024 * 1024, // Max total size of elements in eviction queue
                100,                     // Max length of eviction queue
                maxMemory / 8);
        configBuilder.setBitmapMemoryCacheParamsSupplier(
                new Supplier<MemoryCacheParams>() {
                    public MemoryCacheParams get() {
                        return bitmapCacheParams;
                    }
                });
        configBuilder.setMainDiskCacheConfig(diskCacheConfig);
        configBuilder.setDownsampleEnabled(true);
        Fresco.initialize(instance, configBuilder.build());


        NetworkHelper.init(this);
        initNim();

        initIMay();

        AccountManager.getInstance().autoLogin(null);
        if (AccountManager.getInstance().isTokenTimeOut()) {
            ToastUtil.show(this, R.string.str_login_token_time_out);
        }

        IMayCocos.getInstance().createCocosView();
//        FlowManager.bindView(this);
        MessageManager.getInstance().registerSocketListener();

        ActivityHelper.getInstance().setOnAppListener(this);

        //PlayerManager.getInstance().initPlayer(this);

        RoomNoticeHelper.getInstance().requestNotice(); //获取房间公告
    }

    /**
     * 鉴权通知
     */
    public void userLoseNotify() {
        if (AccountManager.getInstance().isLogined()) {
            MessageManager.getInstance().registerLoseNotify();
        }
    }

    @Override
    protected void initAllProcess() {
        UmengPushHelper.getInstance().init(this);
        initNIMClient();
    }

    @Override
    public void exit() {
        super.exit();
        RepostHelper.getInstance().release();
        MessageManager.getInstance().unregisterSocketListener();
        //PlayerManager.getInstance().release();
        MessageManager.getInstance().unregisterLoginLoseListener();
    }

    private void initIMay() {
        if (!BuildConfig.IS_RELEASE) {
            //测试环境
            IMYScheduler.getInstance().setSocketAddress(UrlHelper.getTestSocketDomain(), 7000);
        }
        //初始化框架
        IMYScheduler.getInstance().applicationVersion = BuildConfig.VERSION_NAME;
        //拷贝lua脚本
        String luaFolderName = "config";
        File configFile = new File(getFilesDir(), luaFolderName);
        if (!configFile.exists()) {
            configFile.mkdirs();
            FileUtil.copyFolderFromAssets(this, luaFolderName, configFile.getAbsolutePath());
        }
        IMYScheduler.getInstance().configDirectoryPath = configFile.getAbsolutePath();
        IMYScheduler.getInstance().CAFilePath = configFile.getAbsolutePath() + "/cacert.pem";
        if (!IMYScheduler.getInstance().init()) {
            Log.e("iMay", "IMYScheduler bindView failed");
        } else {
            Log.e("iMay", "IMYScheduler bindView success");
        }
    }

    public boolean isInProtectMode() {
        return mIsProtectMode;
    }

    {
        if (BuildConfig.IS_RELEASE) {
            WXPayEntryActivity.ID = "wx4d36b119ac97c60c";
        } else {
            WXPayEntryActivity.ID = "wxcebfc9743cfed08c";
        }
        PlatformConfig.setWeixin("wx4d36b119ac97c60c", "ba6f380493aaebab91d9cd394934eee3");
        PlatformConfig.setQQZone(AccountManager.QQ_KEY, "taOhbzj3oICVIrYq");
        PlatformConfig.setSinaWeibo("3193089686", "a0c0ca4d76b8df6b08f8dd7042450d1d", "http://www.imay.com/");
    }


    public long getCurrentChatUid() {
        return currentChatUid;
    }

    public void setCurrentChatUid(long currentChatUid) {
        UnreadManager.getInstance().clearRecentUnread(this.currentChatUid);
        this.currentChatUid = currentChatUid;
    }

    @Override
    public void onAppExist() {
    }

    @Override
    public void onAppBackground() {
//        IMayCocos.getInstance().onPause();
        ProtoRequestHelper.task(ProtoSocketFactory.requestRunStatus(2)).setTag(this.hashCode()).request(runStatusCallBack);
        ShareNoticeHelper.getInstance().shareDelayed();
    }

    @Override
    public void onAppForground(final Activity activity) {
//        IMayCocos.getInstance().onResume();
        ProtoRequestHelper.task(ProtoSocketFactory.requestRunStatus(1)).setTag(this.hashCode()).request(runStatusCallBack);
    }

    /**
     * app切换前台后台时发送回调
     */
    ProtoCallBack runStatusCallBack = new ProtoCallBack() {
        @Override
        public void onRequestSuccess(String command, String data) {
            Result<ProtoResult> result = JSON.parseObject(data, new TypeReference<Result<ProtoResult>>() {
            }.getType());
            if (result.result == 1) {

            }
        }

        @Override
        public void onRequestError(String command, int code, String message) {

        }
    };
}
